<template>
    <el-tooltip class="box-item" effect="dark" content="更新头像" placement="bottom">
        <div class="m10" v-if="userInfo">
            <input type="file" ref="fileRef" class="file" @change="todoStartUpload">
            <el-avatar v-if="userInfo.avatar" :src="userInfo.avatar.replace(/public/, baseURL)" :size="35"
                @click="uploadAvatar" />
            <el-avatar v-else :icon="UserFilled" :size="35" @click="uploadAvatar" />

        </div>
    </el-tooltip>
</template>

<script setup lang="ts">
import { UserFilled } from '@element-plus/icons-vue'
import { ref, toRefs } from 'vue';
import { Http } from '../../api/api';
import { baseURL } from '../../api/request';
import { useStore } from '../../store';
const fileRef = ref<any>()
const store = useStore()
const { userInfo } = toRefs(store)
const uploadAvatar = () => {
    fileRef.value.click()
}

const todoStartUpload = async () => {
    const file = fileRef.value.files[0]
    console.log(file)

    const data = new FormData()
    data.append('file', file)

    let res = await Http.uploadfile(data) as unknown as any;
    if (res.code == 200) {

        let data = await Http.changeuserinfo({
            avatar: res.path
        }) as unknown as any;

        if (data.code == 200) {

            store.setUserInfo({
                ...store.userInfo,
                avatar: res.path
            })
        }
    }
}
</script>


<style lang="scss" scoped>
.m10 {
    margin-left: 10px;
    cursor: pointer;
    margin-top: 3px;

    .file {
        display: none;
    }
}
</style>